/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
Ext.define('Nothing.controller.Mains', {
    extend: 'Ext.app.Controller',

    stores: ['Trees'],
    views: ['main.Navigation'],

    refs: [
        {
            ref: 'TabPanel',
            selector: 'tabpanel'
        }
    ],

    init: function () {
        this.control({
            'navigation': {
                itemclick: this.openTab
            }
        });
    },

    openTab: function (view, rec, item, index, e) {
        var me = this,
            options = {};

        if (!rec.isLeaf()) {
            return;
        }

        options.controller = rec.get(me.controlerProperty);
        options.xtype = rec.get(me.xtypeProperty);
        options.iconCls = rec.className || 'x-tree-icon-leaf';

        options[me.tidProperty] = options[me.tidProperty] || rec.getId() || new Date().getTime();

        var tab = me.findTabByTid(options[me.tidProperty]);
        if (!tab) {
            if (options.controller) { // 动态加载 Controller
                this.getController(options.controller);
            }

            Ext.applyIf(options, {
                title: options['title'] || rec.get('name') || rec.get('text'),
                closable: true,
                border: true
            });

            tab = me.addTab(options);
        }

        me.activeTab(tab);
    },

    /**
     * @param title
     * @returns {null}
     */
    findTabByTid: function (tabId) {
        var tabs = this.getTabPanel().items;

        var index = tabs.findIndex(this.tidProperty, tabId);
        return index < 0 ? null : tabs.getAt(index);
    },

    /**
     * private
     * @param options
     */
    addTab: function (options) {
        window.tabs = this.getTabPanel();
        return this.getTabPanel().add(options);
    },

    /**
     *
     * @param tab
     * @returns {*|Ext.Component}
     */
    activeTab: function (tab) {
        return this.getTabPanel().setActiveTab(tab);
    },

    controlerProperty: 'controller',
    xtypeProperty: 'xtype',
    tidProperty: 'tid'
});
